import { rpc } from './rpc'

const wireless = {}

wireless.getDevices = function () {
  return new Promise(resolve => {
    if (this.devices) {
      resolve(this.devices)
      return
    }

    rpc.call('iwinfo', 'devices').then(r => {
      this.devices = r.devices || []
      resolve(this.devices)
    })
  })
}

wireless.getAssoclist = function () {
  return new Promise(resolve => {
    rpc.call('iwinfo', 'allassoclist', {}).then(rsdata => {
      if (!Reflect.has(rsdata.devices, 'assoclist') && !Reflect.has(rsdata, 'devices')) { resolve([]) }
      const deviceList = rsdata.devices
      const assocList = []
      deviceList.forEach(deviceOne => {
        if (Array.isArray(deviceOne.assoclist)) return
        for (const mac in deviceOne.assoclist) {
          const sta = deviceOne.assoclist[mac]
          sta.mac = mac
          sta.hostname = mac
          assocList.push(sta)
        }
      })
      resolve(assocList)
    })
  })
}

export default {
  install (Vue) {
    Vue.prototype.$wireless = wireless
  }
}
